<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品等级" prop="productLevel">
        <el-select v-model="queryParams.productLevel" placeholder="请选择商品等级" clearable @keyup.enter.native="handleQuery">
          <el-option v-for="item in DictData.levelList" :key="item.value" :label="item.name" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="levelName">
        <el-input v-model="queryParams.levelName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="一级分类" prop="countPerformance">
        <el-select v-model="queryParams.countPerformance" placeholder="请选择一级分类" clearable
          @keyup.enter.native="handleQuery">
          <el-option v-for="item in classifyList" :key="item.value" :label="item.name" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否上架" clearable @keyup.enter.native="handleQuery">
          <el-option label="上架" :value="1">
          </el-option>
          <el-option label="下架" :value="2">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:good:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dividendList" @selection-change="handleSelectionChange">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="等级名称" align="center" prop="levelName" />
      <el-table-column label="单个市场业绩" align="center" prop="singlePerformance" />
      <el-table-column label="所需一二市场业绩" align="center" prop="countPerformance" />
      <el-table-column label="当前月金额" align="center" prop="atPresentMoney" />
      <el-table-column label="总共累计金额" align="center" prop="accumulativeTotal" />
      <el-table-column label="奖励类型" align="center" prop="typeName" />
      <el-table-column label="当前人数" align="center" prop="numberOfPeople" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope='{row}'>
          {{ row.status == 1 ? '开启' : '关闭' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-coin" @click="topupHandler(scope.row)"
            v-hasPermi="['system:good:topup']">充值</el-button>
          <el-button size="mini" type="text" icon="el-icon-tickets" v-hasPermi="['system:good:record']"
            @click="recordOpen = true">发放记录</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:good:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:good:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改分红等级对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="14">
            <el-form-item label="等级名称" prop="levelName">
              <el-input v-model="form.levelName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="单个市场业绩" prop="singlePerformance">
              <el-input placeholder="请输入内容" v-model="form.singlePerformance" @input="singlePerformanceChange">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="所需一二市场总业绩" prop="countPerformance">
              <el-input placeholder="空" v-model="form.countPerformance" :disabled="true">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="14">
            <el-form-item label="当前月金额" prop="atPresentMoney">
              <el-input placeholder="请输入内容" v-model="form.atPresentMoney">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="计入分红池商品" prop="productLevel">
              <el-button type="primary" plain @click="chooseGoods">选择商品</el-button>
              <div class="goods-container">
                <div class="goods-item" v-for="item, index in form.productList" :key="item.id">
                  <div class="goods-item-left">
                    <img :src="baseURL + item.goodImg" alt="">
                    <div class="good-item-title">
                      <div>{{ item.goodName }}</div>
                      <div>￥ {{ item.retailPrice }}</div>
                    </div>
                    <el-button icon="el-icon-delete" plain @click="goodsSelectionDelete(index)">删除</el-button>
                  </div>
                  <div class="goods-item-right">
                    <div class="goods-item-label">
                      <span style="color: red;">*</span>
                      <span>分红金额：</span>
                    </div>
                    <div>
                      <el-input placeholder="请输入内容" v-model="item.prizePool">
                        <template slot="append">元</template>
                      </el-input>
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="2" active-text="开启"
                inactive-text="关闭">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <!-- 选择商品列表 -->
      <el-dialog title="计入分红池商品" :visible.sync="goodOpen" width="800px" append-to-body>
        <GoodList  ref="childComp" @tableSelection="tableSelection"></GoodList>
      </el-dialog>
    </el-dialog>

    <!-- 充值金额 -->
    <el-dialog title="充值金额" :visible.sync="topupOpen" width="400px">
      <el-form ref="topupForm" :model="topupForm" label-width="80px">
        <el-form-item label="金额数量" prop="money" :rules="[
          { required: true, message: '请输入金额数量', trigger: 'blur' },
        ]">
          <el-input v-model="topupForm.money" placeholder="请输入金额数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTopupForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 发放记录 -->
    <el-dialog title="发放记录" :visible.sync="recordOpen" width="800px">
      <release-record v-if="recordOpen"></release-record>
    </el-dialog>
  </div>
</template>

<script>
import { getShareOutBonusLevelPage, saveShareOutBonusLevel, updateShareOutBonusLevel, deleteShareOutBonusLevelById, topUpShareOutBonusLevel, getShareOutBonusLevelById } from "@/api/system/dividend/manage.js"
import { forrmatterEnmu } from '@/utils/index'
import GoodList from "./component/goodList.vue"
import ReleaseRecord from "./component/releaseRecord.vue";
export default {
  name: "Good",
  components: { GoodList, ReleaseRecord },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商商品表格数据
      dividendList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        levelName: null,
        countPerformance: null,
        singlePerformance: null,
        productLevel: null,
        status: null,
        atPresentMoney: null,
      },
      // 表单参数
      form: {},
      topupForm: {},
      // 表单校验
      rules: {
        levelName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
      },
      classifyList: [],
      goodOpen: false,
      goodsSelection: [],
      baseURL: process.env.VUE_APP_BASE_API,
      topupOpen: false,
      recordOpen: false
    };
  },
  created() {
    this.getList();
  },
  watch: {
    'form.singlePerformance': function (v) {
      this.form.countPerformance = Number(v) * 2
    }
  },
  methods: {
    forrmatterEnmu,
    chooseGoods(){
      this.goodOpen = true
      this.$refs.childComp.clearSeclect()
    },
    /** 查询供应商商品列表 */
    getList() {
      this.loading = true;
      getShareOutBonusLevelPage(this.queryParams).then(response => {
        this.dividendList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        levelName: null,
        countPerformance: null,
        singlePerformance: null,
        productLevel: null,
        status: 1,
        atPresentMoney: null,
        productList: null,
      };
      this.resetForm("form");
    },
    topupReset() {
      this.form = {
        id: null,
        money: null,
      };
      this.resetForm("topupForm");
    },
    topupHandler(rows) {
      this.topupOpen = true
      this.topupReset()
      this.topupForm.id = rows.id
    },
    tableSelection(v) {
      // console.log('v', v);
      // this.goodsSelection = v
      this.form.productList = v
      this.goodOpen = false
    },
    singlePerformanceChange(v) {
      if (v - 0 === 'NaN') {
        this.$set(this.form, 'singlePerformance', '')
      }
    },
    submitTopupForm() {
      this.$refs['topupForm'].validate(async (v) => {
        if (v) {
          let res = await topUpShareOutBonusLevel(this.topupForm)
          if (res.code == 200) {
            this.$message.success('充值成功')
            this.topupOpen = false
            this.getList()
          }
        }
      })
    },
    // 删除选择的商品
    goodsSelectionDelete(index) {
      this.form.productList.splice(index, 1)
    },
    /**图片上传 */
    uploadImg(file) {
      this.form.goodImg = file
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分红池等级";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getShareOutBonusLevelById({ id }).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分红池等级";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let every = this.form.productList?.every(item => item.prizePool >= 0)
      if (!every && this.form.productList?.length) {
        this.$message.error('分红金额不能为空')
        return
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateShareOutBonusLevel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            saveShareOutBonusLevel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function () {
        return deleteShareOutBonusLevelById(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/good/export', {
        ...this.queryParams
      }, `good_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="less" scoped>
.base-title {
  font-size: 18rpx;
  color: #1a1a1a;
  display: flex;
  align-items: center;
  margin-bottom: 15px;

  &::before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 15px;
    background: #1777FF;
    border-radius: 3px;
    margin-right: 8px;
  }
}

.goods-container {
  .goods-item {
    height: 80px;
    width: 100%;
    margin-top: 20px;
    padding: 0 10px;
    border: 1px solid #c9c9c9;
    display: flex;
    border-radius: 10px;

    .goods-item-left {
      display: flex;
      padding-right: 30px;
      border-right: 1px solid #c9c9c9;
      align-items: center;
      width: 60%;
      height: 100%;

      >img {
        height: 60px;
        width: 60px;
      }

      .good-item-title {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin: 10px 20px;
      }
    }

    .goods-item-right {
      display: flex;
      align-items: center;
      padding-left: 20px;

      .goods-item-label {
        width: 30%;
      }
    }
  }
}
</style>